//
//  RefreshControl.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/9/18.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

// 拖拽的偏移量，超过 -60 旋转箭头
private let GXRefreshMaxOffset :CGFloat = -60

class RefreshControl: UIRefreshControl {

    
    override func endRefreshing() {
        super.endRefreshing()
        
        refresh.stopAnimation()
    }
    
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // KVO 的属性监听
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0
        {
            return
        }
        
        //  如果正在刷新，那么就显示上面小转轮
        if refreshing
        {
            refresh.loadingAnimation()
            return
        }
    
        if frame.origin.y < GXRefreshMaxOffset && !refresh.rotateFlag {
            print("反过来")
            refresh.rotateFlag = true
        } else if frame.origin.y >= GXRefreshMaxOffset && refresh.rotateFlag {
            print("转过去")
            refresh.rotateFlag = false
        }

    }
    
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
    }

    private func setupUI() {
        
        // 隐藏转轮
        tintColor = UIColor.clearColor()
        
        // 0.监听自己的属性
        self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
    
        // 1.添加控件
        addSubview(refresh)
        
        // 2.设置约束
        refresh.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refresh.bounds.size)
    }
    
    
    private lazy var refresh:GXRefreshView = GXRefreshView.refreshView()
}


class GXRefreshView:UIView {
    
    // 定义一个旋转标记
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipAnimation()
        }
    }
    
    @IBOutlet weak var loadingIcon: UIImageView!
    
    @IBOutlet weak var pullDownTipIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!

    
    // 从 xib 中加载视图
    class func refreshView() -> GXRefreshView {
        
        return NSBundle.mainBundle().loadNibNamed("Refresh", owner: nil, options: nil).last! as! GXRefreshView
    }
    
    
    // 箭头反转
    func rotateTipAnimation() {
        
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.01 : 0.01
        UIView.animateWithDuration(0.5) {
            self.pullDownTipIcon.transform = CGAffineTransformRotate(self.pullDownTipIcon.transform, angle)
        }
    }
    
    // 正在刷新
    private func loadingAnimation() {
        
        let loadingAnimKey = "loadingKey"
        
        // 判断是否有动画效果
        if loadingIcon.layer.animationForKey(loadingAnimKey) != nil {
            return
        }
        
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 1
        anim.repeatCount = MAXFLOAT
        
        loadingIcon.layer.addAnimation(anim, forKey: loadingAnimKey)
        
    }
    
    // 停止刷新
    private func stopAnimation() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
}